package org.jivesoftware.smackx.entitycaps;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketInterceptor;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.NotFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ.Type;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.PacketExtension;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.util.Base64;
import org.jivesoftware.smack.util.Cache;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.NodeInformationProvider;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.entitycaps.cache.EntityCapsPersistentCache;
import org.jivesoftware.smackx.entitycaps.packet.CapsExtension;
import org.jivesoftware.smackx.packet.DataForm;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverInfo.Feature;
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;
import org.jivesoftware.smackx.packet.DiscoverItems.Item;

public class EntityCapsManager
{
  public static final String NAMESPACE = "http://jabber.org/protocol/caps";
  public static final String ELEMENT = "c";
  private static final String ENTITY_NODE = "http://www.igniterealtime.org/projects/smack";
  private static final Map<String, MessageDigest> SUPPORTED_HASHES = new HashMap();
  protected static EntityCapsPersistentCache persistentCache;
  private static Map<Connection, EntityCapsManager> instances = Collections.synchronizedMap(new WeakHashMap());
  protected static Map<String, DiscoverInfo> caps = new Cache(1000, -1L);
  protected static Map<String, NodeVerHash> jidCaps = new Cache(10000, -1L);
  private WeakReference<Connection> weakRefConnection;
  private ServiceDiscoveryManager sdm;
  private boolean entityCapsEnabled;
  private String currentCapsVersion;
  private boolean presenceSend = false;
  private Queue<String> lastLocalCapsVersions = new ConcurrentLinkedQueue();

  static
  {
    Connection.addConnectionCreationListener(new ConnectionCreationListener()
    {
      public void connectionCreated(Connection paramAnonymousConnection)
      {
        EntityCapsManager.getInstanceFor(paramAnonymousConnection);
      }
    });
    try
    {
      MessageDigest localMessageDigest = MessageDigest.getInstance("SHA-1");
      SUPPORTED_HASHES.put("sha-1", localMessageDigest);
    }
    catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
    {
    }
  }

  public static void addDiscoverInfoByNode(String paramString, DiscoverInfo paramDiscoverInfo)
  {
    caps.put(paramString, paramDiscoverInfo);
    if (persistentCache != null)
      persistentCache.addDiscoverInfoByNodePersistent(paramString, paramDiscoverInfo);
  }

  public static String getNodeVersionByJid(String paramString)
  {
    NodeVerHash localNodeVerHash = (NodeVerHash)jidCaps.get(paramString);
    if (localNodeVerHash != null)
      return localNodeVerHash.nodeVer;
    return null;
  }

  public static NodeVerHash getNodeVerHashByJid(String paramString)
  {
    return (NodeVerHash)jidCaps.get(paramString);
  }

  public static DiscoverInfo getDiscoverInfoByUser(String paramString)
  {
    NodeVerHash localNodeVerHash = (NodeVerHash)jidCaps.get(paramString);
    if (localNodeVerHash == null)
      return null;
    return getDiscoveryInfoByNodeVer(localNodeVerHash.nodeVer);
  }

  public static DiscoverInfo getDiscoveryInfoByNodeVer(String paramString)
  {
    DiscoverInfo localDiscoverInfo = (DiscoverInfo)caps.get(paramString);
    if (localDiscoverInfo != null)
      localDiscoverInfo = new DiscoverInfo(localDiscoverInfo);
    return localDiscoverInfo;
  }

  public static void setPersistentCache(EntityCapsPersistentCache paramEntityCapsPersistentCache)
    throws IOException
  {
    if (persistentCache != null)
      throw new IllegalStateException("Entity Caps Persistent Cache was already set");
    persistentCache = paramEntityCapsPersistentCache;
    persistentCache.replay();
  }

  public static void setJidCapsMaxCacheSize(int paramInt)
  {
    ((Cache)jidCaps).setMaxCacheSize(paramInt);
  }

  public static void setCapsMaxCacheSize(int paramInt)
  {
    ((Cache)caps).setMaxCacheSize(paramInt);
  }

  private EntityCapsManager(Connection paramConnection)
  {
    this.weakRefConnection = new WeakReference(paramConnection);
    this.sdm = ServiceDiscoveryManager.getInstanceFor(paramConnection);
    instances.put(paramConnection, this);
    paramConnection.addConnectionListener(new ConnectionListener()
    {
      public void connectionClosed()
      {
        EntityCapsManager.this.presenceSend = false;
      }

      public void connectionClosedOnError(Exception paramAnonymousException)
      {
        EntityCapsManager.this.presenceSend = false;
      }

      public void reconnectionFailed(Exception paramAnonymousException)
      {
      }

      public void reconnectingIn(int paramAnonymousInt)
      {
      }

      public void reconnectionSuccessful()
      {
      }
    });
    updateLocalEntityCaps();
    if (SmackConfiguration.autoEnableEntityCaps())
      enableEntityCaps();
    Object localObject = new AndFilter(new PacketFilter[] { new PacketTypeFilter(Presence.class), new PacketExtensionFilter("c", "http://jabber.org/protocol/caps") });
    paramConnection.addPacketListener(new PacketListener()
    {
      public void processPacket(Packet paramAnonymousPacket)
      {
        if (!EntityCapsManager.this.entityCapsEnabled())
          return;
        CapsExtension localCapsExtension = null;
        try
        {
          localCapsExtension = (CapsExtension)paramAnonymousPacket.getExtension("c", "http://jabber.org/protocol/caps");
        }
        catch (Exception localException)
        {
        }
        if (localCapsExtension == null)
          return;
        String str1 = localCapsExtension.getHash().toLowerCase();
        if (!EntityCapsManager.SUPPORTED_HASHES.containsKey(str1))
          return;
        String str2 = paramAnonymousPacket.getFrom();
        String str3 = localCapsExtension.getNode();
        String str4 = localCapsExtension.getVer();
        EntityCapsManager.jidCaps.put(str2, new EntityCapsManager.NodeVerHash(str3, str4, str1));
      }
    }
    , (PacketFilter)localObject);
    localObject = new AndFilter(new PacketFilter[] { new PacketTypeFilter(Presence.class), new NotFilter(new PacketExtensionFilter("c", "http://jabber.org/protocol/caps")) });
    paramConnection.addPacketListener(new PacketListener()
    {
      public void processPacket(Packet paramAnonymousPacket)
      {
        String str = paramAnonymousPacket.getFrom();
        EntityCapsManager.jidCaps.remove(str);
      }
    }
    , (PacketFilter)localObject);
    localObject = new PacketTypeFilter(Presence.class);
    paramConnection.addPacketSendingListener(new PacketListener()
    {
      public void processPacket(Packet paramAnonymousPacket)
      {
        EntityCapsManager.this.presenceSend = true;
      }
    }
    , (PacketFilter)localObject);
    PacketTypeFilter localPacketTypeFilter = new PacketTypeFilter(Presence.class);
    PacketInterceptor local6 = new PacketInterceptor()
    {
      public void interceptPacket(Packet paramAnonymousPacket)
      {
        if (!EntityCapsManager.this.entityCapsEnabled)
          return;
        CapsExtension localCapsExtension = new CapsExtension("http://www.igniterealtime.org/projects/smack", EntityCapsManager.this.getCapsVersion(), "sha-1");
        paramAnonymousPacket.addExtension(localCapsExtension);
      }
    };
    paramConnection.addPacketInterceptor(local6, localPacketTypeFilter);
    this.sdm.setEntityCapsManager(this);
  }

  public static synchronized EntityCapsManager getInstanceFor(Connection paramConnection)
  {
    if (SUPPORTED_HASHES.size() <= 0)
      throw new IllegalStateException("No supported hashes for EntityCapsManager");
    EntityCapsManager localEntityCapsManager = (EntityCapsManager)instances.get(paramConnection);
    if (localEntityCapsManager == null)
      localEntityCapsManager = new EntityCapsManager(paramConnection);
    return localEntityCapsManager;
  }

  public void enableEntityCaps()
  {
    this.sdm.addFeature("http://jabber.org/protocol/caps");
    updateLocalEntityCaps();
    this.entityCapsEnabled = true;
  }

  public void disableEntityCaps()
  {
    this.entityCapsEnabled = false;
    this.sdm.removeFeature("http://jabber.org/protocol/caps");
  }

  public boolean entityCapsEnabled()
  {
    return this.entityCapsEnabled;
  }

  public void removeUserCapsNode(String paramString)
  {
    jidCaps.remove(paramString);
  }

  public String getCapsVersion()
  {
    return this.currentCapsVersion;
  }

  public String getLocalNodeVer()
  {
    return "http://www.igniterealtime.org/projects/smack#" + getCapsVersion();
  }

  public boolean areEntityCapsSupported(String paramString)
  {
    if (paramString == null)
      return false;
    try
    {
      DiscoverInfo localDiscoverInfo = this.sdm.discoverInfo(paramString);
      return localDiscoverInfo.containsFeature("http://jabber.org/protocol/caps");
    }
    catch (XMPPException localXMPPException)
    {
    }
    return false;
  }

  public boolean areEntityCapsSupportedByServer()
  {
    return areEntityCapsSupported(((Connection)this.weakRefConnection.get()).getServiceName());
  }

  public void updateLocalEntityCaps()
  {
    Connection localConnection = (Connection)this.weakRefConnection.get();
    DiscoverInfo localDiscoverInfo = new DiscoverInfo();
    localDiscoverInfo.setType(IQ.Type.RESULT);
    localDiscoverInfo.setNode(getLocalNodeVer());
    if (localConnection != null)
      localDiscoverInfo.setFrom(localConnection.getUser());
    this.sdm.addDiscoverInfoTo(localDiscoverInfo);
    this.currentCapsVersion = generateVerificationString(localDiscoverInfo, "sha-1");
    addDiscoverInfoByNode("http://www.igniterealtime.org/projects/smack#" + this.currentCapsVersion, localDiscoverInfo);
    if (this.lastLocalCapsVersions.size() > 10)
    {
      localObject = (String)this.lastLocalCapsVersions.poll();
      this.sdm.removeNodeInformationProvider("http://www.igniterealtime.org/projects/smack#" + (String)localObject);
    }
    this.lastLocalCapsVersions.add(this.currentCapsVersion);
    caps.put(this.currentCapsVersion, localDiscoverInfo);
    if (localConnection != null)
      jidCaps.put(localConnection.getUser(), new NodeVerHash("http://www.igniterealtime.org/projects/smack", this.currentCapsVersion, "sha-1"));
    Object localObject = new LinkedList(ServiceDiscoveryManager.getInstanceFor(localConnection).getIdentities());
    this.sdm.setNodeInformationProvider("http://www.igniterealtime.org/projects/smack#" + this.currentCapsVersion, new NodeInformationProvider()
    {
      List<String> features = EntityCapsManager.this.sdm.getFeaturesList();
      List<PacketExtension> packetExtensions = EntityCapsManager.this.sdm.getExtendedInfoAsList();

      public List<DiscoverItems.Item> getNodeItems()
      {
        return null;
      }

      public List<String> getNodeFeatures()
      {
        return this.features;
      }

      public List<DiscoverInfo.Identity> getNodeIdentities()
      {
        return this.val$identities;
      }

      public List<PacketExtension> getNodePacketExtensions()
      {
        return this.packetExtensions;
      }
    });
    if ((localConnection != null) && (localConnection.isAuthenticated()) && (this.presenceSend))
    {
      Presence localPresence = new Presence(Presence.Type.available);
      localConnection.sendPacket(localPresence);
    }
  }

  public static boolean verifyDiscoverInfoVersion(String paramString1, String paramString2, DiscoverInfo paramDiscoverInfo)
  {
    if (paramDiscoverInfo.containsDuplicateIdentities())
      return false;
    if (paramDiscoverInfo.containsDuplicateFeatures())
      return false;
    if (verifyPacketExtensions(paramDiscoverInfo))
      return false;
    String str = generateVerificationString(paramDiscoverInfo, paramString2);
    return paramString1.equals(str);
  }

  protected static boolean verifyPacketExtensions(DiscoverInfo paramDiscoverInfo)
  {
    LinkedList localLinkedList = new LinkedList();
    Iterator localIterator1 = paramDiscoverInfo.getExtensions().iterator();
    while (localIterator1.hasNext())
    {
      PacketExtension localPacketExtension = (PacketExtension)localIterator1.next();
      if (localPacketExtension.getNamespace().equals("jabber:x:data"))
      {
        DataForm localDataForm = (DataForm)localPacketExtension;
        Iterator localIterator2 = localDataForm.getFields();
        while (localIterator2.hasNext())
        {
          FormField localFormField1 = (FormField)localIterator2.next();
          if (localFormField1.getVariable().equals("FORM_TYPE"))
          {
            Iterator localIterator3 = localLinkedList.iterator();
            while (localIterator3.hasNext())
            {
              FormField localFormField2 = (FormField)localIterator3.next();
              if (localFormField1.equals(localFormField2))
                return true;
            }
            localLinkedList.add(localFormField1);
          }
        }
      }
    }
    return false;
  }

  protected static String generateVerificationString(DiscoverInfo paramDiscoverInfo, String paramString)
  {
    MessageDigest localMessageDigest = (MessageDigest)SUPPORTED_HASHES.get(paramString.toLowerCase());
    if (localMessageDigest == null)
      return null;
    DataForm localDataForm = (DataForm)paramDiscoverInfo.getExtension("x", "jabber:x:data");
    StringBuilder localStringBuilder = new StringBuilder();
    TreeSet localTreeSet = new TreeSet();
    Object localObject1 = paramDiscoverInfo.getIdentities();
    while (((Iterator)localObject1).hasNext())
      localTreeSet.add((DiscoverInfo.Identity)((Iterator)localObject1).next());
    localObject1 = localTreeSet.iterator();
    while (((Iterator)localObject1).hasNext())
    {
      localObject2 = (DiscoverInfo.Identity)((Iterator)localObject1).next();
      localStringBuilder.append(((DiscoverInfo.Identity)localObject2).getCategory());
      localStringBuilder.append("/");
      localStringBuilder.append(((DiscoverInfo.Identity)localObject2).getType());
      localStringBuilder.append("/");
      localStringBuilder.append(((DiscoverInfo.Identity)localObject2).getLanguage() == null ? "" : ((DiscoverInfo.Identity)localObject2).getLanguage());
      localStringBuilder.append("/");
      localStringBuilder.append(((DiscoverInfo.Identity)localObject2).getName() == null ? "" : ((DiscoverInfo.Identity)localObject2).getName());
      localStringBuilder.append("<");
    }
    localObject1 = new TreeSet();
    Object localObject2 = paramDiscoverInfo.getFeatures();
    while (((Iterator)localObject2).hasNext())
      ((SortedSet)localObject1).add(((DiscoverInfo.Feature)((Iterator)localObject2).next()).getVar());
    Object localObject3 = ((SortedSet)localObject1).iterator();
    while (((Iterator)localObject3).hasNext())
    {
      localObject2 = (String)((Iterator)localObject3).next();
      localStringBuilder.append((String)localObject2);
      localStringBuilder.append("<");
    }
    if ((localDataForm != null) && (localDataForm.hasHiddenFormTypeField()))
      synchronized (localDataForm)
      {
        localObject3 = new TreeSet(new Comparator()
        {
          public int compare(FormField paramAnonymousFormField1, FormField paramAnonymousFormField2)
          {
            return paramAnonymousFormField1.getVariable().compareTo(paramAnonymousFormField2.getVariable());
          }
        });
        Object localObject4 = null;
        Object localObject5 = localDataForm.getFields();
        while (((Iterator)localObject5).hasNext())
        {
          localObject6 = (FormField)((Iterator)localObject5).next();
          if (!((FormField)localObject6).getVariable().equals("FORM_TYPE"))
            ((SortedSet)localObject3).add(localObject6);
          else
            localObject4 = localObject6;
        }
        if (localObject4 != null)
          formFieldValuesToCaps(localObject4.getValues(), localStringBuilder);
        Object localObject6 = ((SortedSet)localObject3).iterator();
        while (((Iterator)localObject6).hasNext())
        {
          localObject5 = (FormField)((Iterator)localObject6).next();
          localStringBuilder.append(((FormField)localObject5).getVariable());
          localStringBuilder.append("<");
          formFieldValuesToCaps(((FormField)localObject5).getValues(), localStringBuilder);
        }
      }
    ??? = localMessageDigest.digest(localStringBuilder.toString().getBytes());
    return Base64.encodeBytes((byte[])???);
  }

  private static void formFieldValuesToCaps(Iterator<String> paramIterator, StringBuilder paramStringBuilder)
  {
    TreeSet localTreeSet = new TreeSet();
    while (paramIterator.hasNext())
      localTreeSet.add((String)paramIterator.next());
    Iterator localIterator = localTreeSet.iterator();
    while (localIterator.hasNext())
    {
      String str = (String)localIterator.next();
      paramStringBuilder.append(str);
      paramStringBuilder.append("<");
    }
  }

  public static class NodeVerHash
  {
    private String node;
    private String hash;
    private String ver;
    private String nodeVer;

    NodeVerHash(String paramString1, String paramString2, String paramString3)
    {
      this.node = paramString1;
      this.ver = paramString2;
      this.hash = paramString3;
      this.nodeVer = (paramString1 + "#" + paramString2);
    }

    public String getNodeVer()
    {
      return this.nodeVer;
    }

    public String getNode()
    {
      return this.node;
    }

    public String getHash()
    {
      return this.hash;
    }

    public String getVer()
    {
      return this.ver;
    }
  }
}

/* Location:           D:\hygieia\userclient\common\libs\easemobchat_2.1.8.jar
 * Qualified Name:     org.jivesoftware.smackx.entitycaps.EntityCapsManager
 * JD-Core Version:    0.6.1
 */